<?php

namespace App\V3\V3_2_6\Services;

use App\Helper\Utils\Util;
use App\V3\V3_2_6\Models\MaterielClassModel;
use App\V3\V3_2_6\Models\MaterielTypeModel;
use Illuminate\Support\Facades\DB;

class MaterielClassService
{
    /**
     * 商品分类列表
     * @param $mainId 主账号id
     * @param $data['pageSize'] 页面大小即显示条数
     * @param $data['currentPage'] 当前页
     * @param $data['keyword'] 关键词
     * @param $data['class_id'] id标识
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/3 14:52
     * @return mixed
     */
    static public function index($mainId, $data)
    {
        $condition = [];
        $condition1 = [];
        if(!empty($data['materiel_class_id'])) {
            $condition['b.id'] = ['EQ' => $data['materiel_class_id']];
            $condition1['materiel_class_id'] = ['EQ' => $data['materiel_class_id']];
        }

        $keyword = empty($data['keyword'])?'':$data['keyword'];

        $result = self::materielClassList($mainId, $data, $condition, $condition1, $keyword);
//        switch($data['type']) {
//            case 0:
//                $result = self::materielClassList($mainId, $data, $condition, $condition1, $keyword);
//                break;
//            default:
//                $result = self::productList($mainId, $data, $condition, $condition1, $keyword);
//        }

        return $result;
    }

    private static function productList($mainId, $data, array $condition, array $condition1, $keyword)
    {
               
            if(!empty($condition) || $keyword != '') {
                $result = self::withSearchProductList($mainId, $data, $condition, $condition1, $keyword);
            }
            else {
                $result = self::withoutSearchProductList($mainId, $data);
            }
        
        return $result;
    }

    private static function withoutSearchProductList($mainId, $data)
    {
        return MaterielClassModel::withoutSearchProductList($mainId, $data);
    }

    protected static function materielClassList($mainId, $data, $condition, $condition1, $keyword)
    {       
        $firstClassInfo=[];
        if(!empty($data['materiel_class_id']) && empty($keyword)) {
            $firstClassInfo = MaterielClassModel::where([
                'parent_id' => 0,
                'id' => $data['materiel_class_id']
            ])->first();
        }
        if(!empty($firstClassInfo)){//如果点击是的一级分类返回二级分类
            $data['p_id']=$firstClassInfo['id'];
            $result = self::withoutSearchMaterielClassList($mainId, $data);
        }else{
             if(!empty($condition) || $keyword != '') {
    
                $result = self::withSearchMaterielClassList($mainId, $data, $condition, $condition1, $keyword);
            }else {    
                $result = self::withoutSearchMaterielClassList($mainId, $data);
            }
        }

        return $result;
    }

    static public function withSearchMaterielClassList($parentId, $data, $condition, $condition1, $keyword)
    {
        
        $typeInfo = MaterielClassModel::getMaterielAndClassInfo($parentId, $condition, $keyword, $data);       
        $firstClass = [];
        $secondClass = [];
        foreach($typeInfo as $k => $v) {
            $firstClass[] = $v['f_id'];
            $secondClass[] = $v['s_id'];
        }

        return MaterielClassModel::select(
            'id',
            'class_name',
            'class_no',
            'is_product_class'
        )
            ->from('materiel_class')
//            ->where('is_product_class', 0)
            ->where('main_id', $parentId)
            ->with('nextClass', function($query) use ($secondClass, $condition1, $keyword) {
                $query->select(
                    'id',
                    'class_name',
                    'class_no',
                    'parent_id',
                    'is_product_class'
                )
                    ->where('delete_flag', 0)
//                    ->where('is_product_class', 0)
                    ->with('nextType', function($query) use ($condition1, $keyword) {
                        $query->select(
                            'id',
                            'materiel_name',
                            'type_name',
                            /* 'materiel_img', */
                            'materiel_no',
                            'materiel_class_id',
                            /* 'remark', */
                            'is_product_materiel'
                        )
                            ->where($condition1)
                            ->where('delete_flag', 0)
                            ->where(function($query) use ($keyword) {
                                $query->orWhere('materiel_name', 'LIKE', '%'.$keyword.'%');
                                $query->orWhere('type_name', 'LIKE', '%'.$keyword.'%');
                                $query->orWhere('materiel_no', 'LIKE', '%'.$keyword.'%');
                            });
                    })
                    ->whereIn('id', array_unique($secondClass));
            })
            ->where('parent_id', 0)
            ->where('delete_flag', 0)
            ->whereIn('id', array_unique($firstClass))
            ->orderBy('id', 'asc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
    }

    static public function withoutSearchMaterielClassList($parentId, $data)
    {
        $query = MaterielClassModel::select(
            'id',
            'class_name',
            'class_no',
            'is_product_class'
        )
            ->from('materiel_class')
            ->where('main_id', $parentId);
            if(!empty($data['p_id'])){
                $query->with('nextClass', function($query) {
                    $query->select(
                        'id',
                        'class_name',
                        'class_no',
                        'parent_id',
                        'is_product_class'
                    )->where('delete_flag', 0);                 
                })->where('id', $data['p_id']);
            }
            $query->where('parent_id', 0);
            $info = $query->where('delete_flag', 0)
            ->orderBy('id', 'asc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        return $info;
    }

    //物料商品分类下拉列表
    static public function select($mainId, $isProductClass)
    {
        $condition = [];
        if(isset($isProductClass)) {
            $condition[] = ['is_product_class', '=', $isProductClass];
        }

        return MaterielClassModel::select(
            'id', 'class_name', 'class_no', 'is_product_class'
        )->with('nextClass', function($query) {
            $query->select(
                'id', 'class_name', 'class_no', 'parent_id', 'is_product_class'
            )->where('delete_flag', 0)->orderBy('id', 'desc');
        })
            ->where($condition)
            ->where([
                'main_id' => $mainId,
                'delete_flag' => 0,
                'parent_id' => 0
            ])->orderBy('id', 'desc')->get();
    }

    //新建商品分类
    static public function add($mainId, $data)
    {
        //type->0:一级分类;1:二级分类;
        if($data['type']) {
            if($data['parent_id'] == 0) {
                return ['code' => 1, 'msg' => '请选择一级商品分类'];
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_no' => $data['class_no'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_name' => $data['class_name'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }
        else {
            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_no' => $data['class_no'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_name' => $data['class_name'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }

        unset($data['type']);

        $insertId = MaterielClassModel::insertGetId($data);
        return ['code' => 0, 'data' => $insertId];
    }

    //校验分类是否存在-通过id
    static public function checkClass($id)
    {
        return MaterielClassModel::where('id', $id)->where('delete_flag', 0)->first();
    }

    //检查下一级分类有无
    static public function checkNext($id)
    {
        $info = MaterielClassModel::where('id', $id)->where('delete_flag', 0)->first();

        if($info['parent_id'] == 0) {
            if(!empty(MaterielClassModel::where(['parent_id' => $id, 'delete_flag' => 0])->first())) {
                return 1;
            }
            else {
                return 0;
            }
        }
        else {
            //该二级分类下是否存在未删除的
            if(!empty(MaterielTypeModel::where(['materiel_class_id' => $id, 'delete_flag' => 0])->first())) {
                return 2;
            }
            else {
                return 0;
            }
        }
    }

    //编辑商品分类信息
    static public function edit($data)
    {
        $info = MaterielClassModel::where('id', $data['id'])->where('delete_flag', 0)->first();

        if(empty($info)) {
            return 0;
        }

//        if($info['is_product_class']) {
//            return 5;
//        }

        //type->0:一级分类;1:二级分类;
        if($data['type']) {
            if($info['parent_id'] == 0) {
                return 1;
            }

            if($data['parent_id'] == 0) {
                return 2;
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' => $data['parent_id'],
                'class_no' => $data['class_no'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0,
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_name' => $data['class_name'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            if(!empty($checkNoInfo)) {
                return 3;
            }

            if(!empty($checkNameInfo)) {
                return 4;
            }
        }
        else {
            if($info['parent_id'] != 0) {
                return 1;
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_no' => $data['class_no'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0,
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            if(!empty($checkNoInfo)) {
                return 3;
            }

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_name' => $data['class_name'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0,
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            if(!empty($checkNameInfo)) {
                return 4;
            }
        }

        unset($data['type']);

        MaterielClassModel::where('id', $data['id'])->update($data);
        return 5;
    }

    public static function createdDefaultProductWarehouse($mainId)
    {
        $getProductWarehouseInfo = MaterielClassModel::where([
            'is_product_class' => 1,
            'main_id' => $mainId
        ])->first();

        if(empty($getProductWarehouseInfo)) {
            $fClassNo = self::randNo($mainId);

            $fClassId = MaterielClassModel::insertGetId([
                'class_name' => '默认成品库',
                'class_no' => $fClassNo,
                'is_product_class' => 1,
                'main_id' => $mainId,
                'created_at' => time()
            ]);

            $sClassNo = self::randNo($mainId);

            MaterielClassModel::insert([
                'class_name' => '套餐组合',
                'class_no' => $sClassNo,
                'full_class_no' => $fClassNo.$sClassNo,
                'parent_id' => $fClassId,
                'is_product_class' => 1,
                'main_id' => $mainId,
                'created_at' => time()
            ]);
        }

        return true;
    }

    //校验物料分类随机code
    public static function randNo($mainId)
    {
        $classNo = Util::randStr(4);

        while(!empty(MaterielClassModel::checkMaterielClassCode($classNo, $mainId))) {
            $classNo = Util::randStr(4);
        }

        return $classNo;
    }
}
